package com.zz.ecommerce.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Http工具类
 *
 * @author zhangmeng
 * @date 2015-11-24
 */
public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * httpPost请求
     *
     * @param url          请求地址
     * @param requestParam 请求参数
     * @return
     * @throws IOException
     */
    public static String httpPost(String url, Map<String, Object> requestParam) throws IOException {
        String responseStr = "";
        URL postUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);

        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf8");
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        String content = getRequestParam(requestParam);
        out.writeBytes(content);

        out.flush();
        out.close();

        responseStr = convertStreamToString(connection.getInputStream(), "utf8");
        connection.disconnect();
        return responseStr;
    }

    /**
     * 生成请求参数
     *
     * @param requestParam
     * @return
     */
    private static String getRequestParam(Map<String, Object> requestParam) throws UnsupportedEncodingException {
        String content = "";
        if (null != requestParam) {
            for (Map.Entry<String, Object> entry : requestParam.entrySet()) {
                content += ("&" + entry.getKey() + "=" + URLEncoder.encode(String.valueOf(entry.getValue()), "utf8"));
            }
        }
        return content.replaceAll("^&", "");
    }


    /**
     * 从流中读取字符串
     *
     * @param is
     * @param charSet
     * @return
     */
    public static String convertStreamToString(InputStream is, String charSet) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, charSet));
            String line;
            while (null != (line = reader.readLine())) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            logger.error("读取http返回流失败:", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                logger.error("读取http返回流失败:", e);
            }
        }
        return sb.toString();
    }

}
